import Sortable from 'sortablejs';

export default {
    data() {
        return {
            isSorting: false,
            refreshing: false,
            sortData: [],
        }
    },
    methods: {
        initSort() {
            let el = this.$el.querySelector('.el-table__body-wrapper tbody');
            this.sortable = Sortable.create(el, {
                //animation: 50,
                handle: '.sort-handle',
                //  ghostClass: 'over-row',
                onEnd: evt => { // 监听拖动结束事件
                    var item = this.sortData.splice(evt.oldIndex, 1)[0]
                    this.sortData.splice(evt.newIndex, 0, item)
                }
            })
        },
        startSort() {
            this.sortData = this.dataList.map(row => row.id)
            this.isSorting = true
            this.switchCol1(true)
            this.$nextTick(this.initSort)
        },
        stopSort() {
            this.isSorting = false
            if (this.sortable) {
                this.sortable.option('disabled', true)
                if (this.sortable.el) this.sortable.destroy()
            }
        },

        loadForSort() {
            var pageInfo = {
                page: 1,
                pageSize: 400,
            }
            this.loadListBy(pageInfo, undefined).then(t => {
                this.startSort()
            })
        },
        switchCol1(isSort) {
            var colHandle = this.tableHead.find(c => c.slot === 'handle_c')
            if (colHandle) colHandle.hidden = !isSort
            var selection = this.tableHead.find(c => c.type === 'selection')
            if (selection) selection.hidden = isSort
        },
        stopSortAndReload(isSearch) {
            this.stopSort()

            // 由于sortablejs绑定了el-table，需要强制刷新表格
            this.refreshing = true
            this.$nextTick(t => {
                this.refreshing = false
                this.loadList(isSearch).finally(t => {
                    this.switchCol1(false)
                })
            })
        },
    },
    destroyed() {
        this.sortable = null
    }
}
